//
//  Ugc_Release_VC_WX.m
//  ZITHER
//
//  Created by weixin on 2018/9/11.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "Ugc_Release_VC_WX.h"
#import "JZProgressView.h"
#import "UGCReleaseAddImage.h"

#import "NetworkEngine+imageCloudManager.h"

typedef void(^AskImageUploadBlock)(BOOL isSuccess, NSString *imageURLs);

@interface Ugc_Release_VC_WX ()<QMUITextViewDelegate>

@property (nonatomic,strong)QMUITextView * textView;
@property(nonatomic, assign) CGFloat textViewMinimumHeight;
@property(nonatomic, assign) CGFloat textViewMaximumHeight;
@property (nonatomic,strong)QMUILabel * leb;
@property (nonatomic,strong)QMUILabel * labProgress;
@property (nonatomic,strong)JZProgressView *progressView;
@property(nonatomic, strong) UILabel *tipsLabel;
@property (nonatomic,strong)UGCReleaseAddImage * viewImage;

/** 上传图片名称 */
@property (nonatomic,strong)NSMutableArray * arrMPicName;


@end

@implementation Ugc_Release_VC_WX

- (void)textViewDidChangeSelection:(UITextView *)textView{
    NSLog(@"字数 : %ld",textView.text.length);
    // 0-120 圈 120-140 文字   140以后 红字 红圈  150以后 圈没了 红字

    NSInteger textLength = textView.text.length;
    if (textLength<120) {
        self.labProgress.hidden = YES;
        self.progressView.hidden = NO;
        self.progressView.progressColor = baseColorRepainting;
        
    }else if (textLength<=140){
        self.labProgress.text = [NSString stringWithFormat:@"%ld",140-textLength];
        self.labProgress.textColor = baseColorRepainting;
        self.labProgress.hidden = NO;
        self.progressView.hidden = NO;
        self.progressView.progressColor = baseColorRepainting;
        
    }else if (textLength<150){
        self.labProgress.text = [NSString stringWithFormat:@"%ld",140-textLength];
        self.labProgress.textColor = baseColorForegroundError;
        self.labProgress.hidden = NO;
        self.progressView.hidden = NO;
        self.progressView.progressColor = baseColorForegroundError;
        
    }else{
        self.labProgress.text = [NSString stringWithFormat:@"%ld",140-textLength];
        self.labProgress.textColor = baseColorForegroundError;
        self.labProgress.hidden = NO;
        self.progressView.hidden = YES;
        self.progressView.progressColor = baseColorForegroundError;
        }
    self.progressView.progressValue = (textLength)/140.0;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNav];
    [self setUI];
    
    self.textView.delegate = self;
}


-(void)setNav{
    [self.baseNavigationView setHiddenNav:YES VC:self];

    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    self.navigationController.navigationBar.shadowImage = [UIImage new];
//    [self.baseNavigationView setBackgroundColor:[UIColor clearColor]];
//    self.baseNavigationView.bottomLineView.backgroundColor = [UIColor clearColor];
//    self.baseNavigationView.leftButton1.hidden = YES;
    
    QMUIButton *btn = [[QMUIButton alloc]initWithFrame:CGRectMake(14,kStatusBarHeight+5,40,40)];
    [btn setImage:[UIImage imageNamed:@"common_back"] forState:UIControlStateNormal];
    [self.view addSubview:btn];
    @weakify(self);
    [[btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    QMUIButton *btnSend = [[QMUIButton alloc]initWithFrame:CGRectMake(kScreenW-54,kStatusBarHeight+5,40,40)];
    [btnSend setImage:[UIImage imageNamed:@"nav_btn_send"] forState:UIControlStateNormal];
    [self.view addSubview:btnSend];
    [[btnSend rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        //需要收起键盘
        if (self.textView.text.length<=140) {
            if (self.viewImage.arrM.count != 0 || self.textView.text.length != 0) {
                [self send];
            } else {
                [self.view endEditing:YES];
                [Tools showTips:@"内容不许为空"];
            }
        }else {
            [self.view endEditing:YES];
            [Tools showTips:@"字数超过限制"];
        }
        
    }];
    
    self.tabBarController.tabBar.hidden = YES;

}


-(void)setUI{
    
    [self.view addSubview:self.leb];
    [self.view addSubview:self.textView];
    [self.view addSubview:self.progressView];
    [self.view addSubview:self.viewImage];
    [self.view addSubview:self.labProgress];
    @weakify(self);
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.equalTo(self.leb.mas_bottom).offset(50);
        make.left.equalTo(self.view).offset(14);
        make.right.equalTo(self.view).offset(-14);
        make.height.mas_equalTo(100);
    }];
    
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.equalTo(self.textView.mas_bottom).offset(12);
        make.right.equalTo(self.view).offset(-14);
        make.height.width.mas_equalTo(25);
    }];
//    self.viewImage.backgroundColor = [UIColor randomColor];
    [self.viewImage mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.equalTo(self.progressView.mas_bottom).offset(20);
        make.left.equalTo(self.view).offset(14);
        make.right.equalTo(self.view).offset(-14);
        make.height.mas_equalTo(400);
    }];
    
    [self.labProgress mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.center.equalTo(self.progressView).offset(0);
    }];
    
//    QMUITextView
}

-(QMUILabel *)leb{
    if (!_leb) {
        _leb = [[QMUILabel alloc]initWithFrame:CGRectMake(20,kStatusBarHeight+50, 200, 22)];
        _leb.text = @"新创作";
        _leb.font = [UIFont fontWithName:@"Helvetica-Bold" size:22];
        _leb.textColor = [UIColor blackColor];
    }
    return _leb;
}

-(QMUILabel *)labProgress{
    if (!_labProgress) {
        _labProgress = [[QMUILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
        _labProgress.text = @"1";
        _labProgress.font = [UIFont systemFontOfSize:9];
        _labProgress.textColor = [UIColor blackColor];
        _labProgress.textAlignment = NSTextAlignmentCenter;
        _labProgress.hidden = YES;
        self.progressView.centerView = _labProgress;
    }
    return _labProgress;
}

- (JZProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[JZProgressView alloc]initWithFrame:CGRectMake(100,100, 25, 25)];
        _progressView.layer.backgroundColor = [UIColor whiteColor].CGColor;
        _progressView.progressStrokeWidth = 3.f;
        _progressView.progressValue = 0.01;
        _progressView.progressTrackColor = baseColorLight;
        _progressView.progressColor = baseColorRepainting;

    }
    return _progressView;
}

-(QMUITextView *)textView{
    if (!_textView) {
        _textView = [[QMUITextView alloc]initWithFrame:CGRectMake(15, 100, kScreenW-30,300)];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.placeholder = @"请写点你觉得比较猛的事情,但不要太猛";
        _textView.placeholderColor = baseColorLight; // 自定义 placeholder 的颜色
        _textView.textContainerInset = UIEdgeInsetsMake(10, 7, 10, 7);
        _textView.returnKeyType = UIReturnKeyDone;
        _textView.enablesReturnKeyAutomatically = YES;
        _textView.tintColor = [UIColor blackColor];
        _textView.typingAttributes = @{NSFontAttributeName: UIFontMake(18),
                                  NSForegroundColorAttributeName: [UIColor blackColor],
                                  NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:18]};
        // 限制可输入的字符长度
        _textView.maximumTextLength = 400;
        
 
    }
    return _textView;
}

- (UGCReleaseAddImage *)viewImage{
    if (!_viewImage) {
        _viewImage = [[UGCReleaseAddImage alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 300)];
    }
    return _viewImage;
}




#pragma mark - 上传图片
- (void)uploadImageWithPhotos:(NSArray<UIImage *> *)photos completion:(AskImageUploadBlock)completion {
    //  开启菊花
//    [QMUITips showLoadingInView:self.view];
    // 调度组
    dispatch_group_t group = dispatch_group_create();
    // 队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    __block NSMutableArray<NSString *> *uploadURLs = @[].mutableCopy;
    for (NSUInteger i = 0; i< photos.count; i++) {
        UIImage *image = [photos objectAtIndex:i];
        //分别开组
        dispatch_group_enter(group);
        dispatch_group_async(group, queue, ^{
            NSString *date = [NSString currentDateDateFormatter:@"yyyyMM"];
            NSString *path =[NSString stringWithFormat:@"/ugc/%@",date];
            @weakify(uploadURLs);
            
            
//            [kNetworkShared getImageURLWithImagee:image Path:path fileName:nil batchIndex:i completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
//                @strongify(uploadURLs);
//                if (isSuccess) {
//                    [uploadURLs addObject:kSTRING_FORMAT(@"%@/%@",filePath, fileName)];
//                }
//                dispatch_group_leave(group);
//            }];
    
        });
    }
    //完成通知
//    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
////        [QMUITips hideAllTipsInView:self.view];
//        if (uploadURLs.count == photos.count) {
//            NSString *imgURLs = [uploadURLs componentsJoinedByString:@","];
//            // 全部上传成功
//            
//            [[ serviceDefualt loadGetAddUserUgc:self.textView.text fileList:uploadURLs userSubjectId:self.TopicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
//                if (x.success) {
//                    if (completion) {
//                        completion(YES, imgURLs);
//                    }
//                }else{
//                    if (completion) {
//                        completion(NO, nil);
//                    }
//                }
//            }];
//           
//        } else {
//            if (completion) {
//                completion(NO, nil);
//            }
//        }
//    });
}


//-(void)
//{
//
//}

-(void)send{
    
    UgcReleaseFailureModel *modelson = [[UgcReleaseFailureModel alloc]init];
    modelson.content = self.textView.text;
    modelson.arrMPic = [[NSMutableArray alloc]init];
    
    
    //是否有图片
    if (self.viewImage.arrM.count > 0) {
        //有图片  先上传图片
        for (int i =0; i<self.viewImage.arrM.count; i++) {
            [modelson.arrMPic addObject:self.viewImage.arrM[i]];
        }
        @weakify(self);
        
//        arrMPicName
        [self uploadImageWithPhotos:self.viewImage.arrM.copy completion:^(BOOL isSuccess, NSString *imageURLs) {
            @strongify(self);
            if (isSuccess) {
                [Tools showTips:@"发送成功"];
                [self.view endEditing:YES];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                
                [kUSER_INFO_MANAGER addFailureModel:modelson];
                [Tools showTips:@"发送失败"];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }else{
    //没图片
        @weakify(self);
//        [[ serviceDefualt loadGetAddUserUgc:self.textView.text fileList:nil userSubjectId:self.TopicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
//            @strongify(self);
//            if (x.success) {
//                [Tools showTips:@"发送成功"];
//                [self.view endEditing:YES];
//                [self.navigationController popViewControllerAnimated:YES];
//            }else{
//
//                [kUSER_INFO_MANAGER addFailureModel:modelson];
//                [Tools showTips:@"发送失败"];
//                [self.navigationController popViewControllerAnimated:YES];
//            }
//
//        }];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
    
}
@end
